#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Python基础：异常处理
"""

def demonstrate_basic_exceptions():
    """演示基本异常处理"""
    print("=== 基本异常处理示例 ===")
    
    # 处理除零错误
    try:
        result = 10 / 0
    except ZeroDivisionError as e:
        print(f"除零错误: {e}")
    
    # 处理类型错误
    try:
        result = "10" + 5
    except TypeError as e:
        print(f"类型错误: {e}")
    
    # 处理值错误
    try:
        number = int("abc")
    except ValueError as e:
        print(f"值错误: {e}")

def demonstrate_multiple_exceptions():
    """演示多个异常处理"""
    print("\n=== 多个异常处理示例 ===")
    
    def divide_numbers(a, b):
        try:
            result = a / b
            return result
        except ZeroDivisionError:
            print("错误: 除数不能为零")
        except TypeError:
            print("错误: 参数必须是数字")
        except Exception as e:
            print(f"未预期的错误: {e}")
        return None
    
    print(f"10 / 2 = {divide_numbers(10, 2)}")
    print(f"10 / 0 = {divide_numbers(10, 0)}")
    print(f"'10' / 2 = {divide_numbers('10', 2)}")

def demonstrate_finally_block():
    """演示finally块"""
    print("\n=== Finally块示例 ===")
    
    def read_file_with_finally(filename):
        file = None
        try:
            file = open(filename, 'r', encoding='utf-8')
            content = file.read()
            print(f"文件内容: {content}")
        except FileNotFoundError:
            print(f"错误: 文件 '{filename}' 未找到")
        except Exception as e:
            print(f"读取文件时发生错误: {e}")
        finally:
            # 确保文件被关闭
            if file:
                file.close()
                print("文件已关闭")
    
    # 尝试读取不存在的文件
    read_file_with_finally("nonexistent.txt")

def demonstrate_else_block():
    """演示else块"""
    print("\n=== Else块示例 ===")
    
    def convert_to_int(value):
        try:
            number = int(value)
        except ValueError:
            print(f"无法将 '{value}' 转换为整数")
            return None
        else:
            # 只有在没有异常时才执行
            print(f"成功转换: {value} -> {number}")
            return number
        finally:
            print("转换操作完成")
    
    convert_to_int("123")
    print()
    convert_to_int("abc")

def demonstrate_custom_exceptions():
    """演示自定义异常"""
    print("\n=== 自定义异常示例 ===")
    
    class CustomError(Exception):
        """自定义异常类"""
        def __init__(self, message):
            self.message = message
            super().__init__(self.message)
    
    def validate_age(age):
        try:
            if age < 0:
                raise CustomError("年龄不能为负数")
            elif age > 150:
                raise CustomError("年龄不能超过150岁")
            else:
                print(f"有效年龄: {age}")
        except CustomError as e:
            print(f"自定义错误: {e.message}")
    
    validate_age(25)
    validate_age(-5)
    validate_age(200)

def demonstrate_assertions():
    """演示断言"""
    print("\n=== 断言示例 ===")
    
    def calculate_average(numbers):
        assert len(numbers) > 0, "列表不能为空"
        return sum(numbers) / len(numbers)
    
    try:
        avg = calculate_average([1, 2, 3, 4, 5])
        print(f"平均值: {avg}")
        
        # 这会触发断言错误
        avg = calculate_average([])
    except AssertionError as e:
        print(f"断言错误: {e}")

if __name__ == "__main__":
    demonstrate_basic_exceptions()
    demonstrate_multiple_exceptions()
    demonstrate_finally_block()
    demonstrate_else_block()
    demonstrate_custom_exceptions()
    demonstrate_assertions()